#include "base_server.cpp"

static void sig_usr(int);
static void sig_child(int);
static pid_t childPid;

//群聊客户端
int main(){
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    //test data
    portno = GROUP_CHAT_PORT;
    //test end

    //创建socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        error_func("create socket失败", sockfd);
    }

    //准备connect
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(portno);
    if(::connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
        error_func("connect socket失败");
    }
    
    //注册信号
    signal(SIGCHLD, sig_child);
    signal(SIGINT, sig_usr);
    signal(SIGTERM, sig_usr);
    
    childPid = fork();
    if(childPid < 0){
        error_func("fork error");
    }else if(childPid == 0){
        //子进程阻塞在收
        while (1)
        {
            // sleep(4);
            char readBuffer[1024];
            memset(readBuffer , 0 , 1024);
            n = read(sockfd, readBuffer, 1024);
            if(n <= 0){
                printf("服务器已断开连接\n");
                close(sockfd);
                exit(0);
            }else{
                printf("read()=>%s\n", readBuffer);
            }
            
        }
    }else{
        //父进程阻塞在接受屏幕输入，然后发送
        // sleep(2);
        // char sendBuffer[255] = "你好呀，群聊客户端\n";
        // write(sockfd, sendBuffer, strlen(sendBuffer));

        printf("请输入聊天内容...\n");
        while(1){
            char str[1024];
            gets(str);
            write(sockfd, str, strlen(str));
        }
    }

    std::cout<<"通讯结束\n"<<std::endl;
}


static void sig_usr(int signo){
    if(signo == SIGTERM || signo == SIGINT){
        kill(childPid, SIGABRT);
        printf("killed child \n");
    }else{
        printf("catch other signo %d\n", signo);
    }
}

static void sig_child(int signo){
    printf("sign handle SIGCHLD\n");
    wait(NULL);
    exit(0);
}

